﻿using Abp.vNext.WT.WebApi.Issues.MyProject.Issues;
using Abp.vNext.WT.WebApi.Issues;
using NSubstitute;
using System;
using System.Threading.Tasks;
using Xunit;
using Shouldly;
using Volo.Abp;

namespace Abp.vNext.WT.WebApi.Issue_Tests
{
    /// <summary>
    /// 单元测试-领域服务（简洁版）
    /// IssueManager依赖于IssueRepository服务, 在本例中将模拟该服务.
    /// </summary>
    public class IssueManager_TestsShare
    {
        private readonly Guid _userId;
        private readonly IIssueRepository _fakeRepo;
        private readonly IssueManager _issueManager;
        private readonly Issue _issue;

        /// <summary>
        /// 共享测试类构造函数
        /// </summary>
        public IssueManager_TestsShare()
        {
            _userId = Guid.NewGuid();
            _fakeRepo = Substitute.For<IIssueRepository>();
            _issueManager = new IssueManager(_fakeRepo);
            _issue = new Issue();
        }

        [Fact]
        public async Task Should_Assign_An_Issue_To_A_User()
        {
            // Arrange            
            _fakeRepo.GetIssueCountOfUserAsync(_userId).Returns(1);

            // Act
            await _issueManager.AssignToUserAsync(_issue, _userId);

            //Assert
            _issue.AssignedUserId.ShouldBe(_userId);
            await _fakeRepo.Received(1).GetIssueCountOfUserAsync(_userId);
        }

        [Fact]
        public async Task Should_Not_Allow_To_Assign_Issues_Over_The_Limit()
        {
            // Arrange
            _fakeRepo
                .GetIssueCountOfUserAsync(_userId)
                .Returns(IssueManager.MaxAllowedOpenIssueCountForAUser);

            // Act & Assert
            await Assert.ThrowsAsync<BusinessException>(async () =>
            {
                await _issueManager.AssignToUserAsync(_issue, _userId);
            });

            _issue.AssignedUserId.ShouldBeNull();
            await _fakeRepo.Received(1).GetIssueCountOfUserAsync(_userId);
        }
    }
}
